package com.wlf.controller;

import com.alibaba.dubbo.common.utils.StringUtils;
import com.wlf.entity.UtFile;
import com.wlf.service.IFileService;
import com.wlf.template.PolicyTemplate;
import com.wlf.template.VsaTemplate;
import com.wlf.util.FopUtils;
import com.wlf.util.PdfUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.plutext.jaxb.xslfo.Root;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.bind.JAXBContext;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Controller
public class PrintController {


    private JAXBContext content;

    @Autowired
    private FopUtils fopUtils;

    @Autowired
    private PolicyTemplate policyTemplate;

    @Autowired
    private VsaTemplate vsaTemplate;

    @Autowired
    private IFileService fileService;

    private final static  String keyWord="用户（盖章/及或签字）";

    private final static  String filePath="E:\\wei\\资料\\test.pdf";


    @PostConstruct
    public void initMethod(){
        try {
            content=JAXBContext.newInstance(Root.class);
        } catch (Exception e) {
            e.getMessage();
        }
    }

    @RequestMapping(value ="/print")
    public void print(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Root root = policyTemplate.createRoot();
        File file = fopUtils.createTempPdf(root,content);

        response.setContentType("application/pdf;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "inline; filename="+System.currentTimeMillis()+".pdf");

        OutputStream out =response.getOutputStream();
        InputStream inStream = new FileInputStream(file);// 文件的存放路径
        BufferedInputStream bis = new BufferedInputStream(inStream);
        byte [] buf = new byte[2048];
        int len=0;
        while((len=bis.read(buf)) !=-1)
            out.write(buf, 0, len);
        bis.close();
        out.flush();
        if(out !=null) {
            out.close();
        }
       if(file.exists()){
           file.delete();
       }
    }

    @RequestMapping(value ="/vsa")
    public void vsa(HttpServletRequest request, HttpServletResponse response) throws Exception {

        Root root = vsaTemplate.createRoot();
        File file = fopUtils.createTempPdf(root,content);

        response.setContentType("application/pdf;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "inline; filename="+System.currentTimeMillis()+".pdf");

        OutputStream out =response.getOutputStream();
        InputStream inStream = new FileInputStream(file);// 文件的存放路径
        BufferedInputStream bis = new BufferedInputStream(inStream);
        byte [] buf = new byte[2048];
        int len=0;
        while((len=bis.read(buf)) !=-1)
            out.write(buf, 0, len);
        bis.close();
        out.flush();
        if(out !=null) {
            out.close();
        }
        if(file.exists()){
            file.delete();
        }
    }

    /**
     * 去读本地文件
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value ="/localPrint")
    public void localPrint(HttpServletRequest request, HttpServletResponse response,UtFile utFile) throws Exception {

        if(utFile == null || StringUtils.isBlank(utFile.getUuid())){
            throw new Exception("参数异常");
        }
        //根据uuid查询数据库
        UtFile f = fileService.getfile(utFile);
        if(f == null){
            throw new Exception("未获取到文件");
        }
        response.setContentType("application/pdf;charset=UTF-8");
        response.setHeader("Content-Disposition",
                "inline; filename="+System.currentTimeMillis()+f.getFileName().substring(f.getFileName().lastIndexOf("."),f.getFileName().length()));

        File file = new File(f.getFileName());
        OutputStream out =response.getOutputStream();
        InputStream inStream = new FileInputStream(file);// 文件的存放路径
        BufferedInputStream bis = new BufferedInputStream(inStream);
        byte [] buf = new byte[2048];
        int len=0;
        while((len=bis.read(buf)) !=-1)
            out.write(buf, 0, len);
        bis.close();
        out.flush();
        if(out !=null) {
            out.close();
        }
    }

    /**
     * PDF签名
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value ="/printPdfFile")
    public void printPdfFile(HttpServletRequest request, HttpServletResponse response,String signName) throws Exception {
        try {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition",
                    "inline; filename=print.pdf");
            File file = new File(filePath);
            byte[] pdfData = PdfUtils.fileBytes(file);
            //5.调用方法，给定关键字和文件
            List<float[]> positions = PdfUtils.findKeywordPostions(pdfData, keyWord);
            if(CollectionUtils.isNotEmpty(positions)){
                float[] pos =positions.get(positions.size()-1);
                List<PdfUtils.PdfItextModel> list = new ArrayList<>();
                System.out.println("正在第"+(int) pos[0]+" 页增加签名，坐标 X:"+pos[1]+" Y:"+(pos[2]-40f));
                list.add(new PdfUtils.PdfItextModel(pos[1],(pos[2]-45f),(int) pos[0],signName));
                File tempFile =File.createTempFile(UUID.randomUUID().toString(),".pdf");
                PdfUtils.responseFile(tempFile,list,pdfData);
                OutputStream out =response.getOutputStream();
                InputStream inStream = new FileInputStream(tempFile);// 文件的存放路径
                BufferedInputStream bis = new BufferedInputStream(inStream);
                byte [] buf = new byte[2048];
                int len=0;
                while((len=bis.read(buf)) !=-1)
                    out.write(buf, 0, len);
                bis.close();
                out.flush();
                if(out !=null) {
                    out.close();
                }
                if(tempFile !=null && tempFile.exists()){
                    tempFile.delete();
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * PDF签名
     * @param request
     * @param response
     * @throws Exception
     */
    @RequestMapping(value ="/printPdf")
    public void printPdf(HttpServletRequest request, HttpServletResponse response,String signName) throws Exception {
        OutputStream out = null;
        try {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition",
                    "inline; filename=print.pdf");
            File file = new File(filePath);
            byte[] pdfData = PdfUtils.fileBytes(file);
            out =response.getOutputStream();
            //5.调用方法，给定关键字和文件
            List<float[]> positions = PdfUtils.findKeywordPostions(pdfData, keyWord);
            if(CollectionUtils.isNotEmpty(positions)){
                float[] pos =positions.get(positions.size()-1);
                List<PdfUtils.PdfItextModel> list = new ArrayList<>();
                System.out.println("正在第"+(int) pos[0]+" 页增加签名，坐标 X:"+pos[1]+" Y:"+(pos[2]-40f));
                list.add(new PdfUtils.PdfItextModel(pos[1],(pos[2]-45f),(int) pos[0],signName));
                PdfUtils.res(out,list,pdfData);
            }

        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
